﻿
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Caching;
using System.Xml.Linq;


namespace BugManager
{
    public class ErrorManager
    {
        private const string ErrorLogFolder = "/ErrorLog";
        private static readonly bool AllowWriteErrorToFile = ConfigurationManager.AppSettings["WriteErrorToFile"] != null && ConfigurationManager.AppSettings["WriteErrorToFile"] == "TRUE";
        private static readonly bool DebugMode = ConfigurationManager.AppSettings["DebugMode"] != null && ConfigurationManager.AppSettings["DebugMode"] == "1";
        private static readonly string Format = Environment.NewLine + "Request page: {0}" + Environment.NewLine + "Error at: {1} " + Environment.NewLine + "Function name: {2}" + Environment.NewLine + "Error message: {3}";
        //private const string AppKey = "U29oYS52bg==";
        //private static readonly ErrorManagerService ErrorLog = new ErrorManagerService();
        private const string DefaultGmailUsername = "channelvnlog.sohanews@gmail.com";
        private const string DefaultGmailPassword = "channelvn";

        public static void Log(string noiPhatSinhLoi, string tenHamPhatSinhLoi, string loi)
        {
            var txtError = string.Format(Format, HttpContext.Current.Request.Url.AbsolutePath, noiPhatSinhLoi, tenHamPhatSinhLoi, loi);
            Log(txtError);
        }

        public static void Log(string error)
        {
            if (DebugMode)
            {
                WriteErrorToFile(error);
                return;
            }
            try
            {
                error = string.Format("REQUEST URL : {0}{1} REFER URL : {3}{1} MESSAGE : {2}",
                                      HttpContext.Current.Request.RawUrl,
                                      Environment.NewLine,
                                      error,
                                      HttpContext.Current.Request.UrlReferrer);

                SendMail("gianghoangtruong@vccorp.vn",
                    null,
                    string.Format("Log.SohaNews - {0}", DateTime.Now.ToString("dd/MM/yyyy HH:mm")),
                    error,
                    null);
            }
            catch
            {
                if (AllowWriteErrorToFile)
                {
                    if (!string.IsNullOrEmpty(error))
                    {
                        WriteErrorToFile(error);
                    }
                }
            }
        }

        public class CreateLogFiles
        {
            private readonly string _sLogFormat;
            private readonly string _sErrorTime;

            public CreateLogFiles()
            {
                _sLogFormat = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + " ==> ";
                var sYear = DateTime.Now.Year.ToString();
                var sMonth = DateTime.Now.Month.ToString();
                var sDay = DateTime.Now.Day.ToString();
                _sErrorTime = sYear + sMonth + sDay;
            }

            public void ErrorLog(string sPathName, string sErrMsg)
            {
                var sw = new StreamWriter(sPathName + "\\Error_" + _sErrorTime + ".txt", true);
                sw.WriteLine(_sLogFormat + sErrMsg);
                sw.Flush();
                sw.Close();
            }
        }

        [Serializable]
        public class GmailInfo
        {
            public string Username { get; set; }
            public string Passwords { get; set; }
        }

        public class LogConfig
        {
            public static GmailInfo GetGmailInfo()
            {
                const string cacheName = "GmailInfo";

                var result = HttpContext.Current.Cache.Get(cacheName) as GmailInfo;
                if (result == null)
                {
                    var fullPath = HttpContext.Current.Server.MapPath("/App_Data/channelvnLogConfig.xml");


                    if (File.Exists(fullPath))
                    {
                        var doc = XElement.Load(fullPath);
                        var gmailConfigs = doc.Descendants("gmail");
                        var xElements = gmailConfigs as XElement[] ?? gmailConfigs.ToArray();
                        var account = xElements.FirstOrDefault();
                        if (account != null)
                        {
                            result = new GmailInfo
                                {
                                    Username = account.Attribute("username") != null ? (string)account.Attribute("username") : string.Empty,
                                    Passwords = account.Attribute("passwords") != null ? (string)account.Attribute("passwords") : string.Empty
                                };
                            var cacheDependency = new CacheDependency(fullPath);
                            HttpContext.Current.Cache.Add(cacheName, result, cacheDependency, DateTime.Now.AddMonths(1),
                                                          Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                        }

                    }
                }
                return result;
            }

        }


        private const string Host = "smtp.gmail.com";
        private const int Port = 587;
        public static void SendMail(string receiver, string[] cc, string subject, string body, Attachment attachment)
        {
            string username;
            string password;
            var gmailAccount = LogConfig.GetGmailInfo();
            if (gmailAccount != null)
            {
                username = gmailAccount.Username;
                password = gmailAccount.Passwords;
            }
            else
            {
                username = DefaultGmailUsername;
                password = DefaultGmailPassword;
            }

            var fromAddress = new MailAddress(username);
            var toAddress = new MailAddress(receiver);

            var smtp = new SmtpClient(Host, Port)
                {
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, password)
                };

            var mailMsg = new MailMessage(fromAddress, toAddress);
            if (cc != null && cc.Length > 0)
            {
                foreach (string s in cc)
                {
                    mailMsg.Bcc.Add(s);
                }
            }
            mailMsg.Subject = subject;
            mailMsg.Body = body;
            if (attachment != null)
            {
                mailMsg.Attachments.Add(attachment);
            }
            mailMsg.IsBodyHtml = true;
            smtp.Send(mailMsg);
        }

        private static void WriteErrorToFile(string error)
        {

            try
            {
                var err = new CreateLogFiles();
                err.ErrorLog(HttpContext.Current.Server.MapPath(ErrorLogFolder), error);
            }
            catch
            {
                return;
            }

        }

        public static void Log(Exception ex)
        {
            Log(ex.ToString());
        }
    }
}
